package com.efounder.message.socket;

import com.efounder.message.socket.JFSocketHandler.OnChannelActiveListener;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;


public class JFSocketInitializer extends ChannelInitializer<SocketChannel> {
//    private TCPClientSSLContextFactory  factory;
//    public JFSocketInitializer(){
//        factory = new TCPClientSSLContextFactory();
//        factory.init();
//    }
    private OnChannelActiveListener onChannelActiveListener;
    private JFSocketHandler handler;
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //todo ssl证书 start
//        if(factory.getClientContext()!=null)
//        {
//            SSLEngine engine = factory.getClientContext().createSSLEngine();
//            engine.setUseClientMode(true);
//            ch.pipeline().addLast(new SslHandler(engine));
//        }
        //todo ssl证书 end
//        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));  
//        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));  
//        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));  
        //客户端的逻辑  
        handler = new JFSocketHandler();
        handler.setOnChannelActiveListener(this.onChannelActiveListener);
        pipeline.addLast(new MessageSplitHandler());
//        ch.pipeline().addLast("idleStateHandler",new IdleStateHandler(2000,2000,2000, TimeUnit.MILLISECONDS));
        pipeline.addLast(handler);
    }

    public void setOnChannelActiveListener(
            OnChannelActiveListener onChannelActiveListener) {
        this.onChannelActiveListener = onChannelActiveListener;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        System.out.println("---channelRead--- msg="+msg);
        super.channelRead(ctx, msg);
    }



    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("---channelReadComplete---");
        super.channelReadComplete(ctx);
    }
}
